package controll;

import java.io.IOException;
import java.util.LinkedList;

import com.google.gdata.client.media.ResumableGDataFileUploader;
import com.google.gdata.util.ServiceException;

import model.Constants;
import model.YouTubeEntry;
import model.YoutubeChannel;
import services.UserYoutubeService;
import services.YoutubeUploadService;

public class UploadController {
	ResumableGDataFileUploader uploader;
	
	public synchronized boolean  uploadVideosforChannel(YoutubeChannel youtubechannel)
	{
		UserYoutubeService youTubeService = youtubechannel.getUserYouTubeService();
		LinkedList<YouTubeEntry> youTubeVideoUploadList = youtubechannel.getUploadQueue();
		for(YouTubeEntry youTubeVideo : youTubeVideoUploadList){
			YoutubeUploadService userUploadClient = new YoutubeUploadService(youTubeService.getYoutubeService());
			boolean uploadFailed = false;
			try {
				uploader= userUploadClient.uploadVideo(youTubeVideo);
				uploader.start();
			    while (userUploadClient.getFileUploadProgressListener().getStatus() == Constants.UPLOAD_IN_PROGRESS) {
			        	Thread.sleep(Constants.PROGRESS_UPDATE_INTERVAL);
			        	youTubeVideo.setInsertProgress(userUploadClient.getFileUploadProgressListener().getProgress());
			      }
			    if(userUploadClient.getFileUploadProgressListener().getStatus()!= Constants.UPLOAD_COMPLETE)
			    {
			    	uploadFailed = true;
			    }
			} catch (IOException e) {
				uploadFailed = true;
				e.printStackTrace();
			} catch (ServiceException e) {
				uploadFailed = true;
				e.printStackTrace();
			} catch (InterruptedException e) {
				uploadFailed = true;
				e.printStackTrace();
			} finally {
				youTubeVideo.setInstertToYouTubeFailed(uploadFailed);
			}
			

		}
		return true;
	}
	
	
}
	
	
	

